package com.sina.shop.manage.dao.menu;

import com.sina.shop.dao.ShopDataSourceDao;
import com.sina.shop.domain.menu.Menu;
import com.sina.shop.domain.menu.Menu_;
import com.sina.shop.domain.menu.Type;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * description:
 * 段浩杰 2017-12-27 23:15
 */
@Repository("menuManageDao")
public class MenuManageDaoImpl extends ShopDataSourceDao implements MenuManageDao {

    @Override
    public Menu getMenuByName(String name) {
        String hql = "from Menu where name=:name";
        return unique(hql, new String[]{"name"}, new Object[]{name});

    }

    @Override
    public int deleteMenu(Long id) {
        String hql = "delete from Menu m where m.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);

            return query.executeUpdate();
        });
    }

    @Override
    public List<Map<String, Object>> getMenuList(Menu menu) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Menu> root = criteriaQuery.from(Menu.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    menuSelection(root)
            );

            Predicate predicate = menuPredicate(menu, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.asc(root.get(Menu_.menu)),
                    builder.asc(root.get(Menu_.sort))
            );

            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //得到起始条数
            int first = (menu.getPage() - 1) * menu.getRows();

            query.setFirstResult(first);
            query.setMaxResults(menu.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    /**
     * 查询条件组装类
     *
     * @param menu
     * @param builder
     * @param root
     * @return
     */
    protected Predicate menuPredicate(Menu menu, CriteriaBuilder builder
            , Root<Menu> root) {
        List<Predicate> list = new ArrayList<>(4);

        if (menu.getLastId() != null) {
            list.add(
                    builder.lt(root.get(Menu_.id), menu.getLastId())
            );
        }

        if (menu.getName() != null) {
            list.add(
                    builder.like(root.get(Menu_.name), "%" + menu.getName() + "%")
            );
        }

        if (menu.getCreateStart() != null) {
            list.add(
                    builder.greaterThanOrEqualTo(root.get(Menu_.createTime), menu.getCreateStart())
            );
        }

        if (menu.getCreateEnd() != null) {
            list.add(
                    builder.lessThanOrEqualTo(root.get(Menu_.createTime), menu.getCreateEnd())
            );
        }
        //if (documents.getStatus() != null) {
        /*list.add(
                builder.equal(root.get(Carousel_.status), Status.USE)
        );*/
        //}

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }


    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> menuSelection(Root<Menu> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(Menu_.id).as(Long.class).alias("id"));//id
        list.add(root.get(Menu_.name).alias("name"));//
        list.add(root.get(Menu_.menu).alias("menu"));
        list.add(root.get(Menu_.sort).alias("sort"));
        list.add(root.get(Menu_.type).alias("type"));

        list.add(root.get(Menu_.createTime).alias("createTime"));//
        list.add(root.get(Menu_.updateTime).alias("updateTime"));//
        list.add(root.get(Menu_.createName).alias("createName"));


        return list;
    }

    @Override
    public List<Map<String, Object>> getMenuIdAndNameList(Boolean hasAll) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Menu> root = criteriaQuery.from(Menu.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    root.get(Menu_.id).as(Long.class).alias("id"),//id
                    root.get(Menu_.name).alias("name")
            );

            if (!hasAll){
                criteriaQuery.where(
                        builder.equal(root.get(Menu_.type), Type.MEN)
                );
            }
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.asc(root.get(Menu_.menu)),
                    builder.asc(root.get(Menu_.sort))
            );

            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public Long getMenuCount(Menu menu) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<Menu> root = criteriaQuery.from(Menu.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(Menu_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    menuPredicate(menu, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }
}
